<template>
  <div class="department-container">
    <div class="app-container">
      <el-card>
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="first">
            <el-button type="primary" @click="Add"> +新增角色 </el-button>
            <!-- 表格 -->
            <el-table :data="tableData" style="width: 100%">
              <el-table-column type="index" label="序号" width="50" />
              <el-table-column prop="name" label="名称" width="180" />
              <el-table-column prop="description" label="描述" />
              <el-table-column prop="address" width="300" label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="success"
                    @click="assign(scope.row.id)"
                  >分配权限</el-button>
                  <el-button
                    size="mini"
                    type="primary"
                    @click="edit(scope.row)"
                  >编辑</el-button>
                  <!-- @click="handleEdit(scope.$index, scope.row)" -->
                  <el-button
                    size="mini"
                    type="danger"
                    @click="del(scope.row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
        <!-- 页脚 -->
        <el-pagination
          background
          :page-size="params.pagesize"
          layout="prev, pager, next"
          :total="total"
          @current-change="hCurrentChange"
        />
        <!-- 弹框 -->
        <el-dialog
          :title="isEdit ? '编辑' : '添加'"
          :visible.sync="showDialog"
          @close="closefn"
        >
          <el-form ref="ruleForm" :model="form" :rules="rules">
            <el-form-item
              label="角色名称"
              :label-width="formLabelWidth"
              prop="name"
            >
              <el-input v-model="form.name" autocomplete="off" />
            </el-form-item>
            <el-form-item
              label="角色描述"
              :label-width="formLabelWidth"
              prop="description"
            >
              <el-input v-model="form.description" autocomplete="off" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="closefn">取 消</el-button>
            <el-button type="primary" @click="hSave">确 定</el-button>
          </div>
        </el-dialog>
        <!-- 分配权限弹框 -->
        <el-dialog
          title="分配权限(一级为路由页面查看权限-二级为按钮操作权限)"
          :visible.sync="showAssignDialog"
        >
          <AssignPermissions ref="permission" :role-id="roleId" @close-assign="showAssignDialog=false" />
          <!-- v-if="showAssignDialog" -->
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import AssignPermissions from './assignPermissions'
import { getRoles, delRoles, addRoles, updateRoles } from '@/api/setting'
export default {
  components: {
    AssignPermissions
  },
  data() {
    return {
      roleId: '',
      isEdit: false, // 编辑状态为true
      activeName: 'first',
      showDialog: false, // 弹框false 隐藏
      showAssignDialog: false, // 分配权限弹框
      tableData: [],
      total: this.total,
      params: {
        page: 1, // 页码
        pagesize: 2 // 每页条数
      },
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '不能为空', trigger: 'blur' }]
      },
      formLabelWidth: '120px'
    }
  },
  created() {
    this.loadRoles()
  },
  methods: {
    // 新增角色按钮
    async doAdd() {
      try {
        const res = await addRoles(this.form)
        console.log('新增角色', res)
        // 1. 重新加载数据
        this.loadRoles()
        // 2. 提示一下
        this.$message.success('操作成功')
        // 3. 关闭弹层
        this.closefn()
      } catch (err) {
        this.$message.error(err.message)
      }
    },
    edit({ id, name, description }) {
      // console.log(row)
      // 数据回填
      // this.roleForm = { id: row.id, name: row.name, description: row.description }
      this.form = { id, name, description }
      this.showDialog = true
      // 3. 设为编辑状态
      this.isEdit = true
    },
    async doEdit() {
      try {
        const res = await updateRoles(this.form)
        console.log('编辑修改之后的结果', res)
        // 1. 重新加载数据
        this.loadRoles()
        this.$message.success('操作成功')
        // 3. 关闭弹层
        this.closefn()
      } catch (err) {
        this.$message.error(err.message)
      }
    },
    // 确定 用户保存
    hSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) {
          return
        }
        // 做具体的添加动作
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    closefn() {
      this.form.name = ''
      this.form.description = ''
      // 2. 移除校验
      this.$refs.ruleForm.clearValidate()
      // 3.关闭弹幕
      this.showDialog = false
    },
    // 用户点击了添加
    Add() {
      this.showDialog = true
      this.isEdit = false
    },
    // 删除
    del(id) {
      this.$confirm('此操作将永久删除该角色吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const res = await delRoles(id)
          console.log('删除角色', res)
          if (this.tableData.length === 1) {
            this.params.page--
            if (this.params.page === 0) {
              this.params.page === 1
            }
          }
          this.loadRoles()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async loadRoles() {
      const res = await getRoles(this.params)
      // console.log('获取角色数据', res)
      this.tableData = res.data.rows
      this.total = res.data.total
    },
    // 分配权限
    assign(id) {
      this.showAssignDialog = true
      this.roleId = id
      if (this.$refs.permission) {
        console.log('子组件', this.$refs.permission)
        this.$nextTick(() => {
          this.$refs.permission.loadRoleDetailById()
        })
      }
    },
    // 用户点击了页码
    hCurrentChange(curPage) {
      // 1. 更新查询条件中页码
      this.params.page = curPage
      // 2. 再发一次请求
      this.loadRoles()
    }
  }
}
</script>

<style>
</style>
